package org.example.structure.decorator;

/**
 * 类描述：装饰器模式
 * <br>
 *
 * @author ZS
 * @version 1.0
 * @date 2020/12/30
 **/
public class DecoratorDemo {
    public static void main(String[] args) {
        // 首先创建需要被装饰的原始对象，即被装饰的对象
        Component component = new ConcreteComponent();

        // 给被装饰的对象增加功能1并调用相关方法
        Decorator decorator = new ConcreteDecorator1(component);
        decorator.operation();

        // 给被装饰的对象增加功能2并调用相关方法
        Decorator decorator1 = new ConcreteDecorator2(component);
        decorator1.operation();

        // 在装饰器1上使用装饰器2
        Decorator decorator2 = new ConcreteDecorator2(decorator);
        decorator2.operation();
    }

    interface Component {
        void operation();
    }

    static class ConcreteComponent implements Component {
        @Override
        public void operation() {
            System.out.println("被装饰的目标方法！");
        }
    }

    abstract static class Decorator implements Component{
        // 持有对象组件
        protected Component component;

        // 构造方法，传入组建对象
        public Decorator(Component component) {
            this.component = component;
        }

        @Override
        public void operation() {
            component.operation();
        }
    }

    static class ConcreteDecorator1 extends Decorator {

        public ConcreteDecorator1(Component component) {
            super(component);
        }

        @Override
        public void operation() {
            System.out.println("装饰1增强！");
            super.operation();
            System.out.println("装饰器1增强！");
        }
    }

    static class ConcreteDecorator2 extends Decorator {

        public ConcreteDecorator2(Component component) {
            super(component);
        }

        @Override
        public void operation() {
            System.out.println("装饰2增强！");
            super.operation();
            System.out.println("装饰器2增强！");
        }
    }
}
